跳到主要内容

101 对称二叉树

https://leetcode.cn/leetbook/read/top-interview-questions-easy/xn08xg/

https://leetcode.cn/problems/validate-binary-search-tree/description/

cost:

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
* right(right) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) { return isSymmetric_(root, root); }

private:
bool isSymmetric_(TreeNode* root, TreeNode* root2) {
if (root == nullptr && root2 == nullptr) {
return true;
}
if (root == nullptr || root2 == nullptr) {
return false;
}
return root->val == root2->val &&
isSymmetric_(root->right, root2->left) &&
isSymmetric_(root->left, root2->right);
}
};
  • 时间复杂度:O(n)
  • 空间复杂度:O(n)